import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { TimerType } from "../../views/Functions/children/Timer/Timer";
import { timerApi } from "../backend/server";

const timerList: TimerType[] = [];

export const timerSlice = createSlice({
  name: "timer",
  initialState: {
    timerList,
  },
  reducers: {
    updateTimerList: (state, action: PayloadAction<TimerType[]>) => {
      return {
        ...state,
        timerList: action.payload,
      };
    },
  },
  extraReducers: (builders) => {
    builders.addCase(fetchTimerList.fulfilled, (state, action) => {
      // console.log(action.payload, state);
      state.timerList = action.payload;
    });
  },
});

export const fetchTimerList = createAsyncThunk<TimerType[], void, {}>(
  "timer/fetchTimerList",
  async (params, action) => {
    return await timerApi.getTimerList();
  }
);

export const timerReducer = timerSlice.reducer;

export const { updateTimerList } = timerSlice.actions;
